<template>
    <div class="affix-container">
        <zh-header-toolbar>
            <zh-button style="margin-left: 8px" button-type="add" @click="dataCenterAdd">新增
            </zh-button>
            <zh-button style="margin-left: 8px" button-type="del" @click="deleteDataCenter">删除
            </zh-button>
            <zh-button style="margin-left: 8px" button-type="save" @click="editDataCenter">编辑</zh-button>
        </zh-header-toolbar>
        <zh-space style="padding-top: 10px">
            <zh-card title="">
                <zh-form ref="dataCenterForm" :model="state.queryParam" :rules="rules">
                    <zh-form-input prop="columnName" label="字段名" placeholder="支持模糊查询"
                                   v-model="state.queryParam.columnName"></zh-form-input>
                    <zh-form-select
                            prop="tableId"
                            label="表Id"
                            :options="state.tableDict"
                            placeholder="请选择"
                            v-model="state.queryParam.tableId"
                    ></zh-form-select>

                    <zh-form-query v-model="state.advanced"  :form-ref="dataCenterForm" @queryClick="clearData"
                                   :table-ref="dataCenterTable"></zh-form-query>
                </zh-form>
            </zh-card>
            <zh-header-toolbar>
                <zh-button style="margin-left: 8px" button-type="save" @click="createCoTableMeta">创建表</zh-button>
            </zh-header-toolbar>

            <zh-table
                    ref="dataCenterTable"
                    title=""
                    funcCode="coTableFieldMeta0001"
                    :columns="state.tableColumn"
                    :disabled="false"
                    highlight-current-row
            >

            </zh-table>
        </zh-space>
        <el-dialog
                ref="dialog"
                v-model="state.dialogVisible"
                title="功能信息"
                width="100%"
        >
            <zh-header-toolbar>
                <zh-button style="margin-left: 8px" button-type="save" @click="saveDataCenter">保存</zh-button>
            </zh-header-toolbar>

            <DataCenterForm ref="dataCenterPage" scroll-height="60vh"/>

        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="DataCenter">
    import {ElMessageBox,ElMessage} from 'element-plus';
    import DataCenterForm from './component/DataCenterForm.vue';
    import {loop} from '@/utils/util';
    import {getCurrentInstance} from "vue";

    const state = reactive({
        tableDict:[],
        advanced:true,
        //弹窗
        dialogVisible: false,
        description: '元数据管理',
        // 基础信息操作按钮是否显示
        infoFlag: true,
        dataCenterInfo: null as any,
        // 路由列表操作按钮是否显示
        routerFlag: false,
        // 功能树
        expandedKeys: [] as any[],
        selectNode: {} as any,
        searchValue: '',
        autoExpandParent: true,
        // 关联路由弹出框
        errors: [] as any[],
        treeUrl: $api.system.getFunctionTreeList.url,
        treeMoveUrl: $api.system.moveFunction.url,
        //查询条件
        queryParam: {} as any,
        dictData: [],
        funcId: '',
        selectRow: {},
        tableColumn: [
            { type: 'checkbox', width: 50, fixed: 'left' },
            {type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号'},
            {field: 'id', title: 'Id', fixed: 'left',  align: 'center', width: 150},
            {field: 'tableId', title: '表Id', fixed: 'left',  align: 'center', width: 150},
            {field: 'columnName', title: '字段名', align: 'center', fixed: 'left', width: 150},
            {field: 'columnComment', title: '字段中文名', align: 'center', fixed: 'left', width: 150},
            {field: 'columnDesc', title: '字段备注', align: 'center',  width: 150},
            {field: 'dataTypeName', title: '字段类型', align: 'center',  width: 200},
            {field: 'dataLength', title: '字段长度', align: 'center',  width: 200},
            {field: 'dataScale', title: '小数位数', align: 'center',  width: 200},
            {field: 'primaryKeyName', title: '主键标志', align: 'center',  width: 200},
            {field: 'nullableName', title: '是否为空', align: 'center',  width: 200},
            {field: 'codeType', title: '代码标识', align: 'center',  width: 200},
            {field: 'safeLevelName', title: '字段分级', align: 'center',  width: 200},
            {field: 'desensitizationName', title: '脱敏类型', align: 'center',  width: 200},
            // {
            //     field: 'funcStatus',
            //     title: '状态',
            //     align: 'center',
            //     editRender: {},
            //     slots: {
            //         // 使用插槽模板渲染
            //         default: 'status_edit',
            //         edit: 'status_edit',
            //     },
            //     width: 120,
            // }
        ],
    });

    //------------------定义子组件---------------------------
    const dataCenterForm = ref<any>({});
    const dataCenterTable = ref<any>({});
    const {isTagsview} = storeToRefs($store.theme);
    const routerForm = ref();
    const dataCenterPage = ref();
    const activeName = ref('baseInfo');
    const saveType = ref('edit');
    const { proxy } = <any>getCurrentInstance();

    const rules = reactive({
        tableId: [
            {
                required: true,
                message: '请输入表Id',
                trigger: 'blur',
            },
        ]
    });

    //------------------定义调用方法-------------------------

    onMounted(() =>{
        getDict();
    })

    // function radioChangeEvent({row}) {
    //     state.funcId = row.funcId;
    //     state.selectRow = row;
    // }

    function handleCurrentChange(row) {
        state.selectRow = row;
        state.funcId = row.funcId;
    }

    // 启用/禁用 功能/接口
    // function onStatusChange(row) {
    //     const params = {
    //         roleId: row.roleId,
    //         status: row.funcStatus,
    //     };
    //     let text = '禁用';
    //     if (params.status == '1') {
    //         text = '启用';
    //     }
    //     $messageBox.success(text + '成功(测试)', '提示');
    //     // setTimeout(() => {
    //     //     $api.common.send
    //     //         .post('role0007', params)
    //     //         .then(() => {
    //     //             $messageBox.success(text + '成功', '提示');
    //     //         })
    //     //         .catch(() => {});
    //     // }, 200);
    // }


    function tabsChange() {
        if (activeName.value === 'baseInfo') {
            findFuncInfo();
            state.infoFlag = true;
            state.routerFlag = false;
        } else if (activeName.value === 'routerList') {
            findFuncInfo();
            routerForm.value.findRouterList();
            state.infoFlag = false;
            state.routerFlag = true;
        }
    }

    function findFuncInfo() {
        if (state.selectNode && state.selectNode.key) {
            const params = {
                funcId: state.selectNode.key,
            };
            $api.common.send.post('dataCenter0002',params).then((res) => {
                state.dataCenterInfo = res.result;
                // 赋值子组件信息
                dataCenterPage.value.setInitDate(res.result);
            }).catch(() => {});
        }
    }

    function editDataCenter() {
        if (state.funcId) {
            nextTick(()=>{
                state.selectNode = {
                    key:state.funcId
                }
                findFuncInfo();
                console.log('state.selectNode',state.selectNode)
            });
        } else {
            ElMessageBox.confirm(
                '请先选择需要操作的功能',
                '提示',
                {
                    confirmButtonText: '确定',
                    type: 'warning',
                    showCancelButton: false
                }
            ).then(() => {

            }).catch(() => {

            })
            return;
        }
        state.dialogVisible = true;
    }

    // function openRouterModel() {
    //     routerForm.value.openRouterModel();
    // }

    function saveDataCenter() {
        //表单验证
        dataCenterPage.value.form.validate((valid) => {
            if (valid) {
                const dataCenterData: any = dataCenterPage.value.dataCenterInfo;
                if (dataCenterData.id) {
                    setTimeout(() => {
                        $api.common.send.post('coTableFieldMeta0005',dataCenterData)
                            .then((res) => {
                                $messageBox.success('修改成功', '提示');
                                dataCenterPage.value.setInitDate(res.result);
                                state.dataCenterInfo = dataCenterPage.value.dataCenterInfo;
                            })
                            .catch(() => {
                            });
                    }, 10);
                } else {
                    setTimeout(() => {
                        $api.common.send.post('coTableFieldMeta0004',dataCenterData)
                            .then((res) => {
                                $messageBox.success('新增成功', '提示');
                                dataCenterPage.value.setInitDate(res.result);
                                state.dataCenterInfo = dataCenterPage.value.dataCenterInfo;
                                state.selectNode = {
                                    key:res.result.funcId
                                }
                            })
                            .catch(() => {
                            });
                    }, 10);
                }
            }
        });
    }

    function dataCenterAdd() {
        state.dialogVisible = true;
        saveType.value = 'add';
       // console.log(dataCenterPage)
        const params = {
            parentId: null as any,
            parentTitle: '',
            funcId: '',
            funcStatus: '1',
            publicFlag: '0',
            nodeType: '0',
            api: '',
            classPath: '',
            orderNo: null as any,
            rate: null as any,
        };
        setTimeout(() => {
            dataCenterPage.value.setInitDate(params);
            state.selectNode = {}
        },100)
    }

    const deleteDataCenter = () => {
        const fileIds:any[] = [];

        const thisChecked = dataCenterTable.value.getAllCheckboxRecords();
        if(thisChecked && thisChecked.length>0){
            thisChecked.forEach((item) =>{
                fileIds.push(item);
            }) ;
        }

        if (fileIds.length == 0) {
            $messageBox.warning('请先选择需要删除的数据', '提示');
            return;
        }
        ElMessageBox({
            title: '删除确认',
            message: h('p', null, [
                h('span', null, '是否确定删除功能'),
                h('i', { style: 'color: teal' }, state.selectRow.tableId),
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true
                    instance.confirmButtonText = '正在删除...'
                    deleteDataCenterSave(instance,done);
                } else {
                    done()
                }
            },
        })
    }

    function deleteDataCenterSave(instance,done) {
        const fileIds:any[] = [];

        const thisChecked = dataCenterTable.value.getAllCheckboxRecords();
        if(thisChecked && thisChecked.length>0){
            thisChecked.forEach((item) =>{
                fileIds.push(item);
            }) ;
        }

        if (fileIds.length>0) {

            setTimeout(() => {
                $api.common.send.post('coTableFieldMeta0008',{coTableFieldMetaVOList:fileIds})
                    .then(() => {
                        done();
                        instance.confirmButtonLoading = false
                        $messageBox.success('删除成功', '提示');
                        state.funcId = '';
                        state.selectRow = {};
                        dataCenterTable.value.refresh();
                        state.selectNode = [];
                        state.dataCenterInfo = null;
                        dataCenterPage.value.setInitDate(null);
                    })
                    .catch(() => {
                        done();
                        instance.confirmButtonLoading = false
                    });
            }, 100);
        } else {
            $messageBox.warning('请先选择需要删除的数据', '提示');
        }
    }

    function clearData(){
        state.funcId = '';
        state.selectRow = {};
        state.dataCenterInfo = {}
    }


    function createCoTableMeta() {
        const fileIds:any[] = [];

        const thisChecked = dataCenterTable.value.getAllCheckboxRecords();
        if(thisChecked && thisChecked.length>0){
           thisChecked.forEach((item) =>{
                fileIds.push(item);
           }) ;
        }

        if (fileIds.length>0){
            console.log("fileIds",fileIds);
            setTimeout(() => {
                $api.common.send.post('coTableFieldMeta0007', {coTableFieldMetaVOList:fileIds})
                    .then(() => {
                        $messageBox.success('创建表成功', '成功提示');
                    })
                    .catch(() => {});
            }, 20);
        }else {
            $messageBox.warning('请先选择建表的的字段','提示');
        }


        }


    //------------------初始化------------------------------
   const getDict = () =>{
       $api.common.send.post('coTableMeta0007', {}).then((res) => {
           state.tableDict = res.result;
       });
   }


</script>

<style lang="less" scoped>

</style>
